//
//  HLLabel.swift
//  weibo1
//
//  Created by changhongliang on 2017/8/26.
//  Copyright © 2017年 richinfo. All rights reserved.
//

//MARK:-处理URL点击有问题,可以找第三方框架研究下

import UIKit

class HLLabel: YLLabel {
    
    override var attributedText: NSAttributedString? {
        didSet{
            //1.将数据存储到storage中
            storage.setAttributedString(attributedText!)
            //2.高亮URL
            matchesURL()
            //3.通知manger重新进行布局
            setNeedsDisplay()
        }

    
    
    }
    
//    override var text: String? {
//        didSet{
//            //1.将数据存储到storage中
//            storage.setAttributedString(NSAttributedString(string: text ?? ""))
//            //2.高亮URL
//            matchesURL()
//            //3.通知manger重新进行布局
//            setNeedsDisplay()
//        }
//    }
    
    override func drawText(in rect: CGRect) {
        //1.让manger重新布局
        //绘制每一个字符
        /*
         第一个参数: 告诉系统需要绘制storage中那些范围数据
         第二个参数:告诉系统从什么位置开始绘制数据
         */
        manger.drawGlyphs(forGlyphRange: NSMakeRange(0, storage.string.characters.count), at: CGPoint.zero)
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSystem()
        //添加点击手势
//        let tap = UITapGestureRecognizer(target: self, action: #selector(HLLabel.labelTap))
//        addGestureRecognizer(tap)
        isUserInteractionEnabled = true
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupSystem()
    }
    
    private func setupSystem(){
        //1.将manger添加到strorage中
        storage.addLayoutManager(manger)
        //2.将container添加到manger中
        container.lineFragmentPadding = 0
        manger.addTextContainer(container)
    
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        container.size = frame.size
    }
    
    private func matchesURL(){
        //1.创建正则表达式子类,告诉系统我们需要匹配URL
        let detector = try! NSDataDetector(types: NSTextCheckingTypes(NSTextCheckingResult.CheckingType.link.rawValue))
        //2.利用正则表达式对象进行匹配
        let res = detector.matches(in: storage.string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, storage.string.characters.count))
        for checkingResult in res {
            let urlStr = (storage.string as NSString).substring(with: checkingResult.range)
            let temp = NSMutableAttributedString(string: urlStr)
            temp.addAttribute(NSForegroundColorAttributeName, value: UIColor.random, range: NSMakeRange(0, urlStr.characters.count))
            storage.replaceCharacters(in: checkingResult.range, with: temp)
            
        }
        storage.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 17.0), range: NSMakeRange(0, storage.string.characters.count))
    
    }
    
    //处理URL点击
   /* override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        //
        urlSet =  Set<URLModel>()
        //1.创建正则表达式子类,告诉系统我们需要匹配URL
        let detector = try! NSDataDetector(types: NSTextCheckingTypes(NSTextCheckingResult.CheckingType.link.rawValue))
        //2.利用正则表达式对象进行匹配
        let res = detector.matches(in: storage.string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, storage.string.characters.count))
        for checkingResult in res {
            //存储URL和位置
            let urlStr = (storage.string as NSString).substring(with: checkingResult.range)
            let urlM = URLModel(url: urlStr, range: checkingResult.range)
            urlSet.insert(urlM)
        }
        //1.获取手指点击的位置
        //1.1获取手指
        let touch = (touches as NSSet).anyObject() as! UITouch
        //1.2获取手指点击的位置
        let point = touch.location(in: touch.view)
        //2.获取URL的范围
        for urlM in urlSet {
            let urlRect = boundingRectForCharacterRange(urlM.urlRange ?? NSRange(location: 0, length: 0))
            HLLog("urlstring:\(urlM.urlString ?? "")")
            HLLog("range:\(String(describing: urlM.urlRange?.location))-----\(String(describing: urlM.urlRange?.length))")
            let view = UIView()
            view.backgroundColor = UIColor.random
            view.frame = urlRect
            addSubview(view)
            if urlRect.contains(point) {
//                HLLog("urlstring:\(urlM.urlString ?? "")")
//                HLLog("range:\(String(describing: urlM.urlRange?.location))-----\(String(describing: urlM.urlRange?.length))")
//            let view = UIView()
//            view.backgroundColor = UIColor.red
//            view.frame = urlRect
//            addSubview(view)
              return
            }
        
        }
        
    }*/
    
    func boundingRectForCharacterRange(_ range: NSRange) -> CGRect {
        var glyphRange = NSRange()
        manger.characterRange(forGlyphRange: range, actualGlyphRange: &glyphRange)
        return manger.boundingRect(forGlyphRange: glyphRange, in: container)
    }
    
    func labelTap(){
    HLLog("")
    
    }
    
    
    
  //懒加载
  /// 专门用于存储数据
  /// manger 需要添加到storage
    private lazy var storage = NSTextStorage()
  
  /// 专门用于管理布局
  //container 需要添加到manger
    private lazy var manger = NSLayoutManager()
  ///专门用于管理范围
    private lazy var container = NSTextContainer()
 /// 用于存储URL和位置
    private var urlSet =  Set<URLModel>()

}

class URLModel: NSObject {
    //存储urlString
    var urlString:String?
    //存储url的range
    var urlRange:NSRange?
    init(url:String, range:NSRange){
        super.init()
        self.urlString = url
        self.urlRange = range
    }
    
}
